/*
    This file is part of Posixcpp library.

    Posixcpp library is free software: you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public License
    as published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Posixcpp library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU LesserGeneral Public
    License along with Posixcpp library. If not, see
    <http://www.gnu.org/licenses/>.
*/
#include "posix_processes_process.hpp"
#include "posixcpp.hpp"

#include <unistd.h>
#include <sys/wait.h>

#include <csignal>
#include <stdlib.h>
#include <termios.h>

using namespace posix::processes;
using namespace posixcpp;

Process::Process( ) :
ActiveObject(EXIT_SUCCESS),
m_pid(0) {

}

Process::Process( pid_t pid ) :
ActiveObject(EXIT_SUCCESS),
m_pid(pid) {

}

Process::~Process( ) {

}

void Process::start( ) {
    POSIX_CALL_ASSERT( (m_pid = fork()) >= 0 );
    if (m_pid == 0) {
        this->run();
        ::exit( this->result().number );
    }
}

int Process::kill( int signo ) {
    return ::kill(m_pid, signo);
}

Process Process::self( ) {
    return Process(::getpid());
}

int Process::wait( int options ) {
    int status;
    
    POSIX_CALL_ASSERT(::waitpid(m_pid, &status, options) != -1);
    
    return status;
}

ActiveObject::ExecutionsRes_t Process::waitFinish( ) {
    return this->wait();
}
